package com.kaaction.modules.market.api;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.kaaction.common.utils.CacheUtils;
import com.kaaction.common.utils.DateUtils;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.utils.WechatUtils;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.weixinpay.WeiXinPay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信接口类
 * 
 * @author zengbiao
 *
 */
@Controller
@RequestMapping(value = "/api/v1/wechat")
public class WechatApiController extends BaseController {
	
	
	/**
	 * 获得openid等信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = { "getid" })
	public void getid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String code = request.getParameter("code");
		logger.info("code=" + code);
		String access_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WechatUtils.APP_ID + "&secret="
				+ WechatUtils.APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
		logger.info("access_url=" + access_url);
		String json = loadJson(access_url);
		Gson gs = new Gson();

		Map<String, String> map = gs.fromJson(json, Map.class);
		String access_token = map.get("access_token");
		CacheUtils.put("access_token", access_token);
		super.writeAjaxResponse(response, map);
	}
	
	@RequestMapping(value = { "ticket" })
	public void ticket(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("try to get ticket ... ");
		Map map = new HashMap();
		String noncestr = UUID.randomUUID().toString().replace("-", "");
		String timestamp = String.valueOf(System.currentTimeMillis()).toString().substring(0, 10);
		String ticket = WechatUtils.getTicket();
		String toEncryStr = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp
				+ "&url=" + request.getParameter("url");
		logger.info("toEncryStr=" + toEncryStr);
		String signature = DigestUtils.sha1Hex(toEncryStr);
		map.put("appId", WechatUtils.APP_ID);
		map.put("ticket", ticket);
		map.put("timestamp", timestamp);
		map.put("noncestr", noncestr);
		map.put("signature", signature);
		
		super.writeAjaxResponse(response, map);
	}

	private void bak(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("try to get ticket ... ");

		String noncestr = UUID.randomUUID().toString().replace("-", "");
		String timestamp = String.valueOf(System.currentTimeMillis()).toString().substring(0, 10);
		Map<String, String> map = new HashMap();

		Object ticketObj = CacheUtils.get("ticket");
		String access_token;
		String ticket;
		if (ticketObj == null) {
			Object tokenObj = CacheUtils.get("access_token_for_ticket");
			if (tokenObj == null) {
				String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
						+ WechatUtils.APP_ID + "&secret=" + WechatUtils.APP_SECRET;
				String jsonx = loadJson(accessUrl);
				Gson gsx = new Gson();

				Map<String, String> mapx = gsx.fromJson(jsonx, Map.class);
				access_token = mapx.get("access_token");
				logger.info("access_token=" + access_token);
				CacheUtils.put("access_token_for_ticket", access_token);
			} else {
				access_token = String.valueOf(tokenObj);
			}

			String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token
					+ "&type=jsapi";
			logger.info("ticket:ticketUrl=" + ticketUrl);
			String json = loadJson(ticketUrl);
			Gson gs = new Gson();

			map = gs.fromJson(json, Map.class);
			ticket = map.get("ticket");
			CacheUtils.put("ticket", ticket);

		} else {
			ticket = String.valueOf(ticketObj);
			map.put("ticket", ticket);
		}
		logger.info("timestamp=" + timestamp);
		String toEncryStr = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp
				+ "&url=" + request.getParameter("url");
		logger.info("toEncryStr=" + toEncryStr);
		String signature = DigestUtils.sha1Hex(toEncryStr);
		map.put("appId", WechatUtils.APP_ID);
		map.put("timestamp", timestamp);
		map.put("noncestr", noncestr);
		map.put("signature", signature);

		logger.info("timestamp=" + timestamp);
		logger.info("noncestr=" + noncestr);
		logger.info("signature=" + signature);

		super.writeAjaxResponse(response, map);
	}
	

		

	public static void main(String[] args) {
		String test = "jsapi_ticket=kgt8ON7yVITDhtdwci0qeW1gGOecu0SCjcrEFY87swgzu7AC0s7nQdYy7ar8krTu7A8kHLdESh_2R1FrAG19AQ"
				+ "&noncestr=9849f42601484ac5975ec0a0286b1be5" + "&timestamp=1493781902"
				+ "&url=http://www.kaaction.com/show/test.html";
		System.out.println(DigestUtils.sha1Hex(test));
	}

	private static String loadJson(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL urlObject = new URL(url);
			URLConnection uc = urlObject.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

}
